package com.cfoco.controller;

import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.afterturn.easypoi.entity.vo.NormalExcelConstants;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.afterturn.easypoi.util.PoiPublicUtil;
import com.cfoco.component.EmployeeValidation;
import com.cfoco.util.ImageUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.cfoco.entity.Breeder;
import com.cfoco.entity.PageBean;
import com.cfoco.service.BreederService;
import com.cfoco.service.FlowtypeService;
import com.cfoco.util.ResponseUtil;
import com.cfoco.util.StringUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/breeder")
@Slf4j
public class BreederController {

	@Resource
	private BreederService breederService;
	
	@Resource FlowtypeService flowtypeService;
	
	@RequestMapping("/login")
	public String login(Breeder breeder,HttpServletRequest request){
		
		Breeder resultbreeder=breederService.login(breeder);
		
		if(resultbreeder==null){
			request.setAttribute("currentBreeder",breeder);
			request.setAttribute("errorMsg", "用户名或密码不正确！");
			return "login";
		}else{
			HttpSession session=request.getSession();
			ServletContext application= request.getSession().getServletContext();
			application.setAttribute("currentBreederapp",resultbreeder);
			
			//RequestContextUtils.getWebApplicationContext(request).getServletContext();
			session.setAttribute("currentBreeder",resultbreeder);
			session.setMaxInactiveInterval(-1);
			return "redirect:/main.jsp";
		}
	}

	
	@RequestMapping("/modifypass")
	public String modifyPassword(Breeder breeder,HttpServletResponse response)throws Exception{
		int resultTotal=breederService.update(breeder);
		JSONObject result=new JSONObject();
		if(resultTotal>0){ // 执行成功
			result.put("success", true);
		}else{
			result.put("success", false);
		}
		ResponseUtil.write(response, result);
		return null;
	}
	
	@RequestMapping("/logout")
	public String logout(HttpSession session)throws Exception{
		session.invalidate();
		return "redirect:/login.jsp";
	}
	
	@RequestMapping("/list")
	public String list(@RequestParam(value="page",required=false)String page,@RequestParam(value="rows",required=false)String rows,Breeder s_breeder,HttpServletResponse response)throws Exception{
		PageBean pageBean=new PageBean(Integer.parseInt(page),Integer.parseInt(rows));
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("brename", StringUtil.formatLike(s_breeder.getBrename()));
		map.put("cardno", StringUtil.formatLike(s_breeder.getCardno()));
		map.put("if_valid",s_breeder.getIf_valid());
		map.put("start", pageBean.getStart());
		map.put("size", pageBean.getPageSize());
		List<Breeder> breederList=breederService.list(map);
		Long total=breederService.getTotal(map);
		JSONObject result=new JSONObject();	 		
		JsonConfig jsonConfig=new JsonConfig();
		jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd hh:mm:ss"));
		JSONArray jsonArray=JSONArray.fromObject(breederList,jsonConfig);
		result.put("rows", jsonArray);
		result.put("rows", jsonArray);
		result.put("total", total);
		ResponseUtil.write(response, result);
		return null;
	}

	/**
	 *
	 * @param breeder 除文件以后的其它数据
	 * @param request 获取文件的存储位置
	 * @param response
	 * @param file 上传文件入参，要与上传图片组件的name一致，否则要用requestparam注解
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/save")
	public String save(Breeder breeder, HttpServletRequest request, HttpServletResponse response, MultipartFile file)throws Exception{
		int resultTotal=0; // 操作的记录条数
		if(breeder.getBreid()==null){
			String url = uploadFile(file, request);
			breeder.setUrl(url);
			resultTotal=breederService.add(breeder);
		}else{
			String url = uploadFile(file, request);
			breeder.setUrl(url);
			resultTotal=breederService.update(breeder);
		}
		JSONObject result=new JSONObject();
		if(resultTotal>0){ // 执行成功
			result.put("success", true);
		}else{
			result.put("success", false);
		}
		ResponseUtil.write(response, result);
		return null;
	}

	private String uploadFile(MultipartFile file,HttpServletRequest request) {

		String imgPath = null;
		ImageUtil imageUtil = new ImageUtil();
		try{
			imgPath= imageUtil.upload(request,file);
			if(imgPath!=null){

			}
		}catch (IOException e) {
			e.printStackTrace();
		}
		return imgPath;

	}

	@RequestMapping("/delete")
	public String delete(@RequestParam(value="ids")String ids,HttpServletResponse response)throws Exception{
		JSONObject result=new JSONObject();
		String []idsStr=ids.split(",");
		for(int i=0;i<idsStr.length;i++){
			breederService.del(Integer.parseInt(idsStr[i]));
		}
		result.put("success", true);
		ResponseUtil.write(response, result);
		return null;
	}
	
	@RequestMapping("/findbreeder")
	public String breederComboList(@RequestParam(value="if_valid",required=false)String if_valid,HttpServletResponse response)throws Exception{
		JSONArray jsonArray=new JSONArray();
		Map<String,Object> map=new HashMap<String,Object>();
		if(if_valid==null){
			map.put("if_valid",1);
		}else {
			map.put("if_valid",Integer.parseInt(if_valid));
		}
		List<Breeder> breederList=breederService.list(map);
		JSONArray rows=JSONArray.fromObject(breederList);
		jsonArray.addAll(rows);
		ResponseUtil.write(response, jsonArray);
		return null;
	}
	
	@RequestMapping("/findbrename")
	public String brenameList(@RequestParam(value="username",required=false)String username,HttpServletResponse response)throws Exception{
		Breeder breeder=breederService.findByNo(username);
		JSONObject json=JSONObject.fromObject(breeder);
		ResponseUtil.write(response,json);
		return null;
	}

	@RequestMapping("export")
	public String export(ModelMap map, HttpServletRequest request){

		//定义表头
		ExportParams params=new ExportParams("饲养员信息","饲养员", ExcelType.XSSF);
		List<Breeder> list;

		//获取数据
		list = breederService.list(null);
		map.put(NormalExcelConstants.DATA_LIST,list);
		map.put(NormalExcelConstants.CLASS,Breeder.class);
		map.put(NormalExcelConstants.PARAMS,params);
		map.put(NormalExcelConstants.FILE_NAME,"饲养员定义表");

		return NormalExcelConstants.EASYPOI_EXCEL_VIEW;
	}

	@RequestMapping("export-template")
	public String exportTemplate(HttpServletResponse response) throws Exception {
		//方式一，通过文件直接下载；方式二，通过easypoi动态生成。

		//方式一 文件模版下载 BufferedInputStream优化读写效率
		File file = new File("D:\\import\\breeder.xlsx");
		FileInputStream fis=new FileInputStream(file);
		byte[] buffer = new byte[fis.available()];
		fis.read(buffer);
		fis.close();

		String filename="breeder-t.xlsx";
		filename= URLEncoder.encode(filename,"UTF-8");
		response.addHeader("Content-Disposition", "attachment;filename=" + filename);
		//response.setContentType("multipart/form-data");

		OutputStream fos = response.getOutputStream();
//		int b;
//		while((b=fis.read())!=-1){
//			fos.write(b);
//		}
		fos.write(buffer);
		fos.flush();
		fos.close();

		return null;

//		//定义表头
//		ExportParams params=new ExportParams("饲养员信息","饲养员", ExcelType.XSSF);
//		List<Breeder> list;
//
//		//获取数据
//		list = breederService.list(null);
//		map.put(NormalExcelConstants.DATA_LIST,list);
//		map.put(NormalExcelConstants.CLASS,Breeder.class);
//		map.put(NormalExcelConstants.PARAMS,params);
//		map.put(NormalExcelConstants.FILE_NAME,"饲养员定义表");
//
//		return NormalExcelConstants.EASYPOI_EXCEL_VIEW;
	}

	@RequestMapping("export-join")
	public String testExport(ModelMap map, HttpServletRequest request){

		//定义表头
		ExportParams params=new ExportParams("测试","测试", ExcelType.XSSF);
		List<Breeder> list;
		//获取数据
		list = breederService.brePigsty();
		map.put(NormalExcelConstants.DATA_LIST,list);
		map.put(NormalExcelConstants.CLASS,Breeder.class);
		map.put(NormalExcelConstants.PARAMS,params);
		map.put(NormalExcelConstants.FILE_NAME,"饲养分配表");

		return NormalExcelConstants.EASYPOI_EXCEL_VIEW;
	}

	@RequestMapping(value = "import",method = RequestMethod.POST)
	public String importTest(@RequestParam("file") MultipartFile file,HttpServletRequest request,HttpServletResponse response) throws Exception {

		JSONObject result = new JSONObject();
		ImportParams params=new ImportParams();
		params.setTitleRows(1);
		params.setHeadRows(1);
		params.setNeedVerify(true);
		//params.setNeedSave(true);
		//params.setVerifyGroup(new Class[]{});

		//File file = new File("D:\\import\\breeder.xlsx");
		//加入自定义验证
		//params.setVerifyHandler(new EmployeeValidation());

		//List<Breeder> breeders = ExcelImportUtil.importExcel(file, Breeder.class, params); 不带校验的导入
		//带检验的导入
		try {
			ExcelImportResult<Breeder> importResult = ExcelImportUtil.importExcelMore(file.getInputStream(), Breeder.class, params);
			if (!importResult.isVerifyFail()) {
				List<Breeder> breeders = importResult.getList();
				for (Breeder breeder : breeders) {
					breederService.add(breeder);
				}
				result.put("success", true);
				//return "redirect:list.do?page=1&rows=10";
			} else {
				FileOutputStream fos = new FileOutputStream("d:/import/error/failwork.xlsx");
				importResult.getFailWorkbook().write(fos);
				fos.flush();
				fos.close();
				result.put("success", false);
				//return "redirect:list.do?page=1&rows=10";
			}


		}catch (Exception e){
			log.info(e.getMessage());
			result.put("success", false);
		}finally {
			ResponseUtil.write(response, result);
		}

		return null;
	}
}